'use strict';

app.controller('cmdbViewCtrl', ["$rootScope","$scope", "$state", "$timeout", "$interval", "$aside", "SweetAlert", "toaster", "Restangular", "api_bpm_domain", "api_configure_data", "api_cmdb", "api_configure_form", function ($rootScope, $scope, $state, $timeout, $interval, $aside, SweetAlert, toaster, Restangular, api_bpm_domain, api_configure_data, api_cmdb, api_configure_form) {

	var width = $scope.width = 650;
	var height = $scope.height = 400;
  var apple_selected, tree, treedata_avm, treedata_geography;
  $scope.my_tree_handler = function (branch) {
        //var _ref;
        var classify=$scope.classify=branch.prefix.toLowerCase()+branch.sign;
        api_cmdb.query({'sign':classify}).then(function(data){
            var myData = Restangular.stripRestangular(data);
            var cmdbview=[];
            var cmdbdata={data:{node:cmdbview}};
             if(myData.data.node.length>0){
              angular.forEach(myData.data.node,function(item){
                if(item.props.removeflag){
                }else{cmdbview.push(item)}
              })
              // for(var i=0;i<myData.data.node.length;i++){
              //   if(myData.data.node[i].props.removeflag){
              //       // myData.data.node.splice(i,1)
              //   }else{
              //     cmdbview.push(myData.data.node[i])
              //   }
              // }
            }
            console.log(cmdbdata);
            if(myData.data&&myData.status==200){
                var ret = myData.data;
                redrawSvg(cmdbdata);
            }            
        });
    };
    $scope.my_data = [];


    function convertListToTree(data, treeMap){
        var idToNodeMap = {}; //Keeps track of nodes using id as key, for fast lookup
        var root = null; //Initially set our loop to null
        var parentNode = null;
        //loop over data
        for(var i = 0; i < data.length; i++) {
            var datum = data[i];
            //each node will have children, so let's give it a "children" poperty
            datum.children = [];

            //add an entry for this node to the map so that any future children can
            //lookup the parent
            idToNodeMap[datum.id] = datum;

            //Does this node have a parent?
            if(typeof datum.parent === "undefined" || datum.parent == null) {
                //Doesn't look like it, so this node is the root of the tree
                root = datum;
                treeMap[datum.id] = root;
            } else {        
                //This node has a parent, so let's look it up using the id
                parentNode = idToNodeMap[datum.parent.id];

                //We don't need this property, so let's delete it.
                delete datum.parent;

                //Let's add the current node as a child of the parent node.
                parentNode.children.push(datum);        
            }
        }
        return root;
    }

    function convertParentToChildList(data){
        var treeMap = {};
        var list=[];
        convertListToTree(data, treeMap);
        angular.forEach(treeMap,function(item){
            list.push(item);
        });
        return list;
    }


    $scope.my_tree = tree = {};
    $scope.try_async_load = function () {
        $scope.my_data = [];
        $scope.select_treedata = [];
        $scope.doing_async = true;
        api_configure_data.fetchDataList('ciclassify',{'idx':0,'sum':100}).then(function(result){
            //console.log(result['list']);
            $scope.select_treedata = $scope.my_data = convertParentToChildList(result['list']);
            $scope.doing_async = false;
            tree.expand_all();
            //console.log(treelist);
        });
    };

    $scope.select_treedata = [];
    $scope.propTypeOptions = [];
    $scope.try_async_load();
  
    $scope.onFilterCallback = function(item){
      //console.log(item);
      if(angular.isDefined(item.children)&&item.children.length>=1){
        //not valid
      }else{
        var tempclassify=item.prefix.toLowerCase()+item.sign;
        $scope.cifilter_classic=tempclassify;
        api_configure_form.renderTabForm(tempclassify).then(function(data){
              var myData = Restangular.stripRestangular(data);
              $scope.propTypeOptions = myData;   
        });
      }      
    }

    $scope.onPropTypeChange = function(form){
      $scope.propOptions = form.fields;  
    }

    $scope.onPropChange = function(prop){
      $scope.cifilter_prop = prop;
    }

    $scope.searchCI = function(searchKey, propObj, ciclassify){
      //if(searchKey!=null&&searchKey.length>1){
        var searchData = {};
        if(angular.isUndefined(propObj)){
          propObj = $scope.cifilter_prop;
        }
        if(angular.isUndefined(ciclassify)){
          ciclassify = $scope.cifilter_classic;
        }
        searchData['sign']=ciclassify;
        if(angular.isDefined(propObj)){
          searchData[propObj.key] = searchKey;
        }
        api_cmdb.query(searchData).then(function(response){
          var data=Restangular.stripRestangular(response);
          //此处不清空nodes
          var node=data.data.node;
          var tempNode=[];
          //nodes 或者links 要去重
          for(var i=0;i<node.length;i++){
            var tmp=0;
            for(var j=0;j<nodes.length;j++){
              if(node[i].uuid==nodes[j].uuid){
                tmp++;
                break;
              }
            }
            if(tmp==0){
                if(node[i].props.removeflag){
                 }else{tempNode.push(node[i]);}
            }
          }
          for(var i=0;i<tempNode.length;i++){//nodes  不清空
            nodes.push(tempNode[i]); 
          }
          
         
          restart();
        })
      //}
      
    }

    $scope.refresh = function(){
      nodes.length=0;
      links.length=0;

      restart();
    }

    $scope.remove = function(){
      if($scope.selected_link==null){
        SweetAlert.swal({
            title: "错误的操作!",
            text: "没有配置项关系被选中!",
            type: "error"
        });
      }else if($scope.selected_node!=null){
        SweetAlert.swal({
            title: "错误的操作!",
            text: "配置项不能在此处删除!",
            type: "error"
        });
      }else if($scope.selected_link.id==-1){
        SweetAlert.swal({
            title: "错误的操作!",
            text: "配置项关系尚未提交，不能删除!",
            type: "error"
        });
      }else if($scope.selected_link!=null){
        var id=$scope.selected_link.id;
        var label = $scope.selected_link.name;
        for(var i=0;i<linkType.length;i++){
          if(linkType[i].type==$scope.selected_link.name){
            label=linkType[i].label;
          }
        }


        SweetAlert.swal({
          title: "确认删除配置项关系-"+ label +"?" ,
          text: "删除配置项关系-"+ label + "以后，你将不能恢复该数据!",
          type: "warning",
          cancelButtonText: "取消",
          showCancelButton: true,
          confirmButtonColor: "#DD6B55",
          confirmButtonText: "确认删除!"
        }, function (isConfirm) {
          if (isConfirm) {
            api_cmdb.removeRef(id).then(function(response){
              if(response&&response.status==200){
                links.splice(links.indexOf($scope.selected_link), 1);
                restart();
              }else{
                SweetAlert.swal({
                  title: "系统错误!",
                  text: "系统错误，请稍候重试或者联系管理员!",
                  type: "error"
                });
              }
            });
          }
        });
      }
    }

    $scope.traversal = function(){
      if($scope.selected_node==null){
        SweetAlert.swal({
            title: "错误的操作!",
            text: "没有配置项被选中!",
            type: "error"
        });
      }else{
        var uuid = $scope.selected_node.uuid;
        api_cmdb.traversal(uuid).then(function(response){
          var d=response.data;
          var node=d.node;
          var link=d.edge;
          var tempNode=[];
          var tempLink=[];
                //nodes 或者links 要去重
          for(var i=0;i<node.length;i++){
            var tmp=0;
            for(var j=0;j<nodes.length;j++){
              if(node[i].id==nodes[j].id){
               tmp++;
               break;
              }
            }
            if(tmp==0){
              tempNode.push(node[i]);
            }
          }
                 
          for(var i=0;i<link.length;i++){
            var tmp=0;
            for(var j=0;j<links.length;j++){
              if(link[i].id==links[j].id){
                tmp++;
                break;
              }
            }
            if(tmp==0){
              tempLink.push(link[i]);
            }
          }
          //数据写入页面
          for(var i=0;i<tempNode.length;i++){//nodes  不清空
            nodes.push(tempNode[i]); 
          }
          for(var i=0;i<tempLink.length;i++){//link  不清空
            links.push(tempLink[i]); 
          }
          //links转换
          for(var i=0;i<links.length;i++){
            for(var j=0;j<nodes.length;j++){
              if(links[i].source==nodes[j].id){
                links[i].source=nodes[j];
              }
              if(links[i].target==nodes[j].id){
                links[i].target=nodes[j];
              }
            }
          }
                
            restart();
        })
      }
    }

	var svg = d3.select('#cmdbSVG').append('svg').attr('width', width).attr('height', height);
	// set up initial nodes and links
	//  - nodes are known by 'id', not by index in array.
	//  - reflexive edges are indicated on the node (as a bold black circle).
	//  - links are always source < target; edge directions are set by 'left' and 'right'.
	var nodes = [],links = [];
	var treeNodes=[];
	//读取labels (node)
	var labels=[];
	//console.log(window.basePath);
	// d3.xhr(window.basePath+"/api/cm/labels").send("GET", function(error, json) {
	// 	if (!error){
	// 		labels=JSON.parse(json.responseText);
	// 		//加载资产类型下拉框
	// 		//treeNodes
	// 		for(var i=0;i<labels.length;i++){
	// 			var tmp=labels[i];
	// 			if(tmp.pid!=null){
	// 				tmp['pid']=tmp['pid'].id;
	// 			}else{
	// 				tmp['pid']=0;
	// 			}
	// 			treeNodes.push(tmp);
	// 		}
	// 		window.labelNodes = treeNodes;
	// 		$.fn.zTree.init($("#treeDemo"), setting, treeNodes);
	// 		//label 类型显示
	// 		d3.select("#rowDiv").selectAll('li')
	// 			.data(labels).enter()
	// 			.append('li')
	// 			.html(function(d){
	// 				return '<i class="icon iconfont">'+d.iconname+'</i><p>'+d.label+'</p>';
	// 			}).on('click',function(d){
	// 				//查询节点
	// 				query(d.sign,"");
	// 			});
	// 	}else{
	// 		jAlert("服务器请求异常",'提示');
	// 	}
	// });


function hideLinkForm(hide){
	$scope.hideLink=hide;
}
function hideFeedForm(hide){
	$scope.hideFeed=hide;
}


function redrawSvg(json){
	nodes.length=0;//先清空
	links.length=0;
	var data=json.data;
	for(var i=0;i<data.node.length;i++){
		 nodes.push(data.node[i]); 
	}
	//TODO
	//hideFeedForm(true);;
	//hideLinkForm(true);
	restart();
}

$scope.query = function(){
  //if(d3.event.keyCode=13){
    queryProp("","");
  //}
}

var queryProp = function(label, prop){
  var data = {sign:label,q:prop};
  api_cmdb.query(data).then(function(response){
    if(response&&(response.status==200)){
      var data=response.data;
      //此处不清空nodes
      for(var i=0;i<data.node.length;i++){
        nodes.push(data.node[i]); 
      }
      restart();
    }else{
      SweetAlert.swal({
              title: "提示!",
              text: "访问服务器出错!",
              type: "error"
            });
    }
  })
}

/*
//查询输入框  回车事件
d3.select("#query").on('keyup',function(){
	if(d3.event.keyCode==13){
		var q=this.value;
		query("",q);
	}
});


//label 查询或者条件查询
function query(label,q){
	 $.ajax({
		 type: "GET",
         url: window.basePath +"/api/cmdb/ci",
         data: {lb :label ,q: q},
         dataType: "json",
         success:function(json){
        	 nodes.length=0;//先清空
        	 links.length=0;
        	 var data=json.data;
        	 for(var i=0;i<data.node.length;i++){
        		 nodes.push(data.node[i]); 
        	 }
        	 hideFeedForm(true);;
        	 hideLinkForm(true);
        	 restart();
         },
         error:function(){
         	SweetAlert.swal({
              title: "提示!",
              text: "访问服务器出错!",
              type: "error"
            });
         }
	 });
}
*/

//读取status (节点  连线)
var statuses=[];
api_configure_data.fetchDataList('cistatus',{'idx':0,'sum':100}).then(function(result){
    if (result&&result.status==200){
    	d3.select('#nodeStatus').selectAll('option')
		 	.data(statuses).enter()
		 	.append('option')
		 	.attr('value',function(d){return d.code;})
		 	.html(function(d){ return d.desc;});    	
	}else{
		SweetAlert.swal({
              title: "提示!",
              text: "服务器请求异常!",
              type: "error"
            });
	}
});
//读取types (node)
// api_configure_data.fetchDataList('cistatus',{'idx':0,'sum':100}).then(function(result){
//     if (result&&result.status==200){
//     	d3.select('#nodeType').selectAll('option')
		 	// .data(types).enter()
		 	// .append('option')
		 	// .attr('value',function(d){return d.source;})
		 	// .html(function(d){ return d.description;});
// 	}else{
// 		SweetAlert.swal({
//               title: "提示!",
//               text: "服务器请求异常!",
//               type: "error"
//             });
// 	}
// });
/*
//读取所有params
initParams();
var params=[];
//更新加载最新的params
function initParams(){
	d3.xhr(window.basePath+"/api/cm/dynparams").send("GET", function(error, json) {
		if (!error){
			params=JSON.parse(json.responseText);
			if(selected_node){
				shownode();
			}else if(selected_link){
				showLink();
			}
		}else{
			jAlert("服务器请求异常","提示");
		}
	});
}
*/
//查询relationship_type表 name 为表里的type,label为显示值
var linkType=[];
function fetchEdgeTypes(){
	api_configure_data.fetchDataList('ciedgetype',{'idx':0,'sum':100}).then(function(response){
		if(response){
			if(response['list']){
				linkType = response['list'];
				d3.select('#linkName').selectAll('option')
				 	.data(linkType).enter()
				 	.append('option')
				 	.attr('value',function(d){return d.type;})
				 	.html(function(d){ return d.label;});
			}else{
				SweetAlert.swal({
	              title: "提示!",
	              text: "服务器请求异常!",
	              type: "error"
	            });
			}
		}else{
			SweetAlert.swal({
              title: "提示!",
              text: "服务器请求异常!",
              type: "error"
            });
		}
	})
}
fetchEdgeTypes();

//设置cost 只能输入整形    最大值为1
// d3.select('#linkCost').on('keyup',function(){
// 	this.value=	this.value.replace(/[^\d.]/g,function(){jAlert('只能输入数字!',"提示");return '';});
// 	if(this.value>1){
// 		jAlert('最大输入值为1','提示');
// 		this.value='';
// 		return;
// 	}
// });

  //添加属性  属性类型
  var proTypes=[
	  {id:1,key:'string',value:'文本类型'},
	  {id:2,key:'date',value:'日期类型'},
	  {id:3,key:'int',value:'数字类型'},
	  {id:4,key:'float',value:'浮点类型'}
  ];
  
// init D3 force layout
var force = d3.layout.force()
    .nodes(nodes)
    .links(links)
    .size([width, height])
    .gravity(.05)
    .linkDistance(150)
    .linkStrength(2)
    .charge(-500)
    .on('tick', tick);

// define arrow markers for graph links
svg.append('svg:defs').append('svg:marker')
    .attr('id', 'end-arrow')
    .attr('viewBox', '0 -5 10 10')
    .attr('refX', 6)
    .attr('markerWidth', 3)
    .attr('markerHeight', 3)
    .attr('orient', 'auto')
  .append('svg:path')
    .attr('d', 'M0,-5L10,0L0,5')
    .attr('fill', '#000');

svg.append('svg:defs').append('svg:marker')
    .attr('id', 'start-arrow')
    .attr('viewBox', '0 -5 10 10')
    .attr('refX', 4)
    .attr('markerWidth', 3)
    .attr('markerHeight', 3)
    .attr('orient', 'auto')
  .append('svg:path')
    .attr('d', 'M10,-5L0,0L10,5')
    .attr('fill', '#000');

// line displayed when dragging new nodes
var drag_line = svg.append('svg:path')
  .attr('class', 'link dragline hidden')
  .attr('d', 'M0,0L0,0');

// handles to link and node element groups
//(1)var path = svg.append('svg:g').selectAll('g')
var path = svg.append('svg:g').selectAll('g'),
    circle = svg.append('svg:g').selectAll('g');

// mouse event vars
var selected_node = null,
    selected_link = null,
    mousedown_link = null,
    mousedown_node = null,
    mouseup_node = null;

function resetMouseVars() {
  mousedown_node = null;
  mouseup_node = null;
  mousedown_link = null;
}

// update force layout (called automatically each iteration)
function tick() {
  // draw directed edges with proper padding from node centers
	path.selectAll('path').attr('d', function(d) {
    var deltaX = d.target.x - d.source.x,
        deltaY = d.target.y - d.source.y,
        dist = Math.sqrt(deltaX * deltaX + deltaY * deltaY),
        normX = deltaX / dist,
        normY = deltaY / dist,
        sourcePadding = d.left ? 27 : 22,
        targetPadding = d.right ? 27 : 22,
        sourceX = d.source.x + (sourcePadding * normX),
        sourceY = d.source.y + (sourcePadding * normY),
        targetX = d.target.x - (targetPadding * normX),
        targetY = d.target.y - (targetPadding * normY);
        
    	
    return 'M' + sourceX + ',' + sourceY + 'L' + targetX + ',' + targetY;
  });
  
  

  circle.attr('transform', function(d) {
    return 'translate(' + d.x + ',' + d.y + ')';
  });
}

// update graph (called when needed)
function restart() {
	//绑定link 数据
	path.datum(links);
  // path (link) group
  path = path.data(links,function(d) { return d.id; });
  
  var p = path.enter().append('svg:g');
  
  //update existing links
  path.selectAll('path').classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; });
  
  // add new links
  p.append('svg:path')
    .attr('class', 'link')
    .attr('id', function(d) { return "path_" + d.id; })
   // .attr('startOffset', '0%')
    .classed('selected', function(d) { return d === selected_link; })
    .style('marker-start', function(d) { return d.left ? 'url(#start-arrow)' : ''; })
    .style('marker-end', function(d) { return d.right ? 'url(#end-arrow)' : ''; })
    .on('mousedown', function(d) {
      if(d3.event.ctrlKey) return;
      
      //去除没有提交的连线
      for(var i=0;i<links.length;i++){
    	  if(links[i].id==-1 && d.id!=-1){
    	  	links.splice(i, 1);
    	  }
      }
       
      // select link
      mousedown_link = d;
      if(mousedown_link === selected_link) {
    	  selected_link =  $scope.selected_link = null;
        selected_node =  $scope.selected_node = null;
    //	  d3.select("#linkDetail").attr('style','display:none');
    	  hideLinkForm(true);//return ;
      	} else {
    	  selected_link = $scope.selected_link = mousedown_link;
        selected_node = $scope.selected_node = null;
    	  //linkName
    	  //d3.select("#linkDetail").attr('style','display:inline-block;width:100%;');  
    	  //showLink();
    	  //show("linkNamebox");//return ;
        openAside(selected_link, linkType);
    	}
      selected_node = $scope.selected_node =  null;

      restart();
    });
  
 
  p.append('svg:text')
  .attr('x', 30)
  .attr('y', 20)
  .attr('class','fontM')
  .append('textPath')
  .attr('xlink:xlink:href',function(d, i){ return "#path_" + d.id; })
  .html(function(d){
	  for(var i=0;i<linkType.length;i++){
		  if(linkType[i].type==d.name){
			  return linkType[i].label;
		  }
	  }
	 });

  // remove old links
  path.exit().remove();


  // circle (node) group
  // NB: the function arg is crucial here! nodes are known by id, not by index!
  circle.datum(nodes);
  circle = circle.data(nodes, function(d) { return d.id; });
  
  // update existing nodes (reflexive & selected visual states)
  circle.selectAll('circle')
    .style('fill', function(d) {return (d === selected_node) ?d3.rgb(colors(d.label)).brighter().toString() : colors(d.label); })
    .style('fill-opacity', 0.75) // add by xi
    .classed('reflexive', function(d) { return d.reflexive; });
	

  // add new nodes
  var g = circle.enter().append('svg:g');
  //g.append('svg:circle').attr('r',22).style('fill','rgb(255,255,255)').style('stroke','rgb(255,255,255)').style('stroke-width','2');
  //g.append('svg:circle').attr('r',24).style('fill','rgb(255,255,255)').style('stroke', function(d) { return d3.rgb(colors(d.label)).darker().toString(); }).style('stroke-width','2');
  g.append('svg:circle').attr('r',24).style('fill', function(d){ return (d === selected_node) ? 'rgb(153,153,153)' : 'rgb(255,255,255)';}).style('stroke', function(d) { return d3.rgb(colors(d.label)).darker().toString(); }).style('stroke-width','2');  
  
  g.append('svg:circle')
    .attr('class', 'node')
    .attr('r', 18)
    .style('fill', function(d) { return (d === selected_node) ? d3.rgb(colors(d.label)).brighter().toString() : colors(d.label); })
    .style('stroke', function(d) { return d3.rgb(colors(d.label)).darker().toString(); })
    .style('fill-opacity', 0.25) //add by xj
    .style('stroke-opacity', 0.5) //add by xj
    .classed('reflexive', function(d) { return d.reflexive; });
  g.on('mouseover', function(d) {
      if(!mousedown_node || d === mousedown_node) return;
      // enlarge target node
      d3.select(this).attr('transform', 'scale(1.1)');
    })
    .on('mouseout', function(d) {
      if(!mousedown_node || d === mousedown_node) return;
      // unenlarge target node
      d3.select(this).attr('transform', '');
    })
    .on('mousedown', function(d) {
      if(d3.event.ctrlKey) return;
      hideLinkForm(true);      
    //去除没有提交的连线
      for(var i=0;i<links.length;i++){
    	  if(links[i].id==-1 ){
    	  	links.splice(i, 1);
    	  }
      }
      // select node
      mousedown_node = d;
      if(mousedown_node === selected_node) {
    	  selected_node = $scope.selected_node = null;
    	  hideFeedForm(true);;
      }else {
    	  selected_node =  $scope.selected_node = mousedown_node;
    	  selected_link = $scope.selected_link = null;
    	  // 点击节点  查询关系及节点 /traversal/{id}/{relation}
            api_cmdb.findRefById(selected_node.id).then(function(result) {
                var d = result.data;
                var node = d.node;
                var link = d.edge;
                var tempNode = [];
                var tempLink = [];
                //nodes 或者links 要去重
                for (var i = 0; i < node.length; i++) {
                    var tmp = 0;
                    for (var j = 0; j < nodes.length; j++) {
                        if (node[i].id == nodes[j].id) {
                            tmp++;
                            break;
                        }
                    }
                    if (tmp == 0) {
                        tempNode.push(node[i]);
                    }
                }

                for (var i = 0; i < link.length; i++) {
                    var tmp = 0;
                    for (var j = 0; j < links.length; j++) {
                        if (link[i].id == links[j].id) {
                            tmp++;
                            break;
                        }
                    }
                    if (tmp == 0) {
                        tempLink.push(link[i]);
                    }
                }
                //数据写入页面
                for (var i = 0; i < tempNode.length; i++) { //nodes  不清空
                    nodes.push(tempNode[i]);
                }
                for (var i = 0; i < tempLink.length; i++) { //link  不清空
                    links.push(tempLink[i]);
                }
                //links转换
                for (var i = 0; i < links.length; i++) {
                    for (var j = 0; j < nodes.length; j++) {
                        if (links[i].source == nodes[j].id) {
                            links[i].source = nodes[j];
                        }
                        if (links[i].target == nodes[j].id) {
                            links[i].target = nodes[j];
                        }
                    }
                }

                restart();
            });
		/*
    	  // 点击节点  查询关系及节点 /traversal/{id}/{relation}
    	  $.ajax({
  			 type: "GET",
  	         url: window.basePath+"/api/cmdb/ci/"+selected_node.id+"/refs",
  	         dataType: "json",
  	         success:function(json){
  	        	 var d=json.data;
  	        	 var node=d.node;
  	        	 var link=d.edge;
  	        	 var tempNode=[];
  	        	 var tempLink=[];
  	        	//nodes 或者links 要去重
  	        	 for(var i=0;i<node.length;i++){
  	        		 var tmp=0;
  	        		 for(var j=0;j<nodes.length;j++){
  	        			 if(node[i].id==nodes[j].id){
  	        				 tmp++;
  	        				 break;
  	        			 }
  	        		 }
  	        		 if(tmp==0){
	        			tempNode.push(node[i]);
  	        		 }
  	        	 }
  	        	 
  	        	 for(var i=0;i<link.length;i++){
  	        		var tmp=0;
  	        		 for(var j=0;j<links.length;j++){
  	        			 if(link[i].id==links[j].id){
  	        				tmp++;
  	        				 break;
  	        			 }
  	        			 
  	        		 }
  	        		if(tmp==0){
	        			tempLink.push(link[i]);
  	        		}
  	        	 }
  	        
  	        	 
  	        	 
  	        	 //数据写入页面
  	        	 for(var i=0;i<tempNode.length;i++){//nodes  不清空
  	        		 nodes.push(tempNode[i]); 
  	        	 }
  	        	for(var i=0;i<tempLink.length;i++){//link  不清空
 	        		 links.push(tempLink[i]); 
 	        	 }
  	        	//links转换
  	        	for(var i=0;i<links.length;i++){
  	        		for(var j=0;j<nodes.length;j++){
  	        			if(links[i].source==nodes[j].id){
  	        				links[i].source=nodes[j];
  	        			}
  	        			if(links[i].target==nodes[j].id){
  	        				links[i].target=nodes[j];
  	        			}
  	        		}
  	        	}
  	        	
  	        	 restart();
  	         },
  	         error:function(){jAlert("访问服务器出错!",'提示');}
  		 });
		*/
    	  //更改编辑内容
    	  //shownode();
      }
     

      // reposition drag line
      drag_line
        .style('marker-end', 'url(#end-arrow)')
        .classed('hidden', false)
        .attr('d', 'M' + mousedown_node.x + ',' + mousedown_node.y + 'L' + mousedown_node.x + ',' + mousedown_node.y);

      restart();
    })
    .on('mouseup', function(d) {
      if(!mousedown_node) return;

      // needed by FF
      drag_line
        .classed('hidden', true)
        .style('marker-end', '');

      // check for drag-to-self
      mouseup_node = d;
      if(mouseup_node === mousedown_node) { resetMouseVars(); return; }

      // unenlarge target node
      d3.select(this).attr('transform', '');

      // add link to graph (update if exists)
      // NB: links are strictly source < target; arrows separately specified by booleans
      var source, target, direction;
      if(mousedown_node.id < mouseup_node.id) {
        source = mousedown_node;
        target = mouseup_node;
        direction = 'right';
      } else {
        source = mouseup_node;
        target = mousedown_node;
        direction = 'left';
      }

      var link;
      link = links.filter(function(l) {
        return (l.source === source && l.target === target);
      })[0];

      if(link) {
    	//变为双向  direction 方向 
        link[direction] = true;
        //更新
        selected_link=link;
	      var l= selected_link;
	      var idVal=l.id;
    	  // 连线提交 TODO  双向提交 后台问题
    	  console.log("put relation type");

    	  //TODO
      	api_cmdb.createRef({'id':l.id,'name':l.name,'source':l.source.id,'target':l.target.id,'left':l.left,'right':l.right}).then(function(resposne){
      		if(response&&response.status==200){
      			selected_link.name=linkName;
            links.push(selected_link);
      			restart();
      		}else{

      		}
      	})
        // $.ajax({
        // 		type: "PUT",
        // 		contentType:"application/json; charset=UTF-8",
        // 	    url: window.basePath+"/api/cmdb/edge/"+idVal,
        // 	    data: JSON.stringify({'id':l.id,'name':l.name,'source':l.source.id,'target':l.target.id,'left':l.left,'right':l.right}),
        // 	    dataType: "json",
        // 	    success:function(data){
        // 			if(data.status==200){
        // 				console.log(data.data.edge[0]);
        				
        // 				selected_link.name=linkName;
        // 				//selected_link.status=linkStatus;
        // 				selected_link.cost=linkCost;
        				
        // 				restart();
        // 				showLink();
        // 			}
        				
        // 		},
        // 	    error: function(data){jAlert("服务器请求异常",'提示');}
        // });
    	
        
      } else {
    	  cancel();
    	  //添加连线
    	  link = {id:-1,source: source, target: target,name:'', left: false, right: false};
    	  link[direction] = true;
    	  selected_link=link;
    	  links.push(link); 
    	  //d3.select("#linkDetail").attr('style','display:inline-block;width:100%;');
    	  //showLink();
    	  openAside(link, linkType);
    	  //show("linkNamebox");
      }
      
      // select new link
      selected_link = $scope.selected_link = link;
      selected_node = $scope.selected_node = null;
      restart();
    });

  // show node name
  g.append('svg:text')
      .attr('x', 0)
      .attr('y', 34) 
      .attr('class', 'id')
      .text(function(d) { return d.name; });//TODO 改为  d.name

  //设置图片	
  g.append('svg:foreignObject')
	.attr("width", 32)
	.attr("height", 32)
	.attr('x', "-16px")
	.attr('y', "-11px")
	.html(function(d){
	 for(var i=0;i<labels.length;i++){
	   if(d.label==labels[i].sign){
 		 return '<i class="icon iconfont">'+labels[i].iconname+'</i>';
 	 }
		 
	 }
});

  // remove old nodes
  circle.exit().remove();

  // set the graph in motion
  force.start();
}

function mousedown() {
  // prevent I-bar on drag
  //d3.event.preventDefault();

  // because :active only works in WebKit?
  svg.classed('active', true);

  if(mousedown_node){
    viewNode(mousedown_node);
  }

  if(d3.event.ctrlKey || mousedown_node || mousedown_link) return;

  // insert new node at point   点击添加node
//  var point = d3.mouse(this),
//      node = {id: ++lastNodeId, reflexive: false};
//  node.x = point[0];
//  node.y = point[1];
//  nodes.push(node);
  
  restart();
}

function viewNode(node){
  if($scope.selected_node.name){
    // var title = $scope.selected_node.name+"-["+$scope.selected_node.uuid+"]";
    if(!$scope.selected_node.props.state||$scope.selected_node.props.state==null){$scope.selected_node.props.state="空"}
    else if($scope.selected_node.props.state){
      if($scope.selected_node.props.state=="1"){$scope.selected_node.props.state="未审核"}
      else if($scope.selected_node.props.state=="2"){$scope.selected_node.props.state="已审核"}
      else if($scope.selected_node.props.state=="3"){$scope.selected_node.props.state="不匹配"}
      else if($scope.selected_node.props.state=="4"){$scope.selected_node.props.state="丢失"}
    };
    if(!$scope.selected_node.name){$scope.selected_node.name="空"};
    if(!$scope.selected_node.status){$scope.selected_node.statu="空"};
    if(!$scope.selected_node.props.useradmin){$scope.selected_node.props.useradmin="空"};
  }
    toaster.pop({
        // type: 'info',
        // title: title,
        body: '<br/><p>搜索代码:' + $scope.selected_node.uuid + '</p>'  +
        '<p>配置标题:' + $scope.selected_node.name + '</p>' +
        '<p>状态:' + $scope.selected_node.status + '</p>' +
        '<p>审核状态:' + $scope.selected_node.props.state + '</p>' +
        '<p>维护人员:' + $scope.selected_node.props.useradmin + '</p>',
        bodyOutputType: 'trustedHtml',
        timeout: 3000
    })
}


function mousemove() {
  if(!mousedown_node) return;

  // update drag line
  drag_line.attr('d', 'M' + mousedown_node.x + ',' + mousedown_node.y + 'L' + d3.mouse(this)[0] + ',' + d3.mouse(this)[1]);

  restart();
}

function mouseup() {
  if(mousedown_node) {
    // hide drag line
    drag_line
      .classed('hidden', true)
      .style('marker-end', '');
  }

  // because :active only works in WebKit?
  svg.classed('active', false);

  // clear mouse event vars
  resetMouseVars();
}

function spliceLinksForNode(node) {
  var toSplice = links.filter(function(l) {
    return (l.source === node || l.target === node);
  });
  toSplice.map(function(l) {
    links.splice(links.indexOf(l), 1);
  });
}

// only respond once per keydown
var lastKeyDown = -1;

function keydown() {
  //d3.event.preventDefault();

  if(lastKeyDown !== -1) return;
  lastKeyDown = d3.event.keyCode;

  // ctrl
  if(d3.event.keyCode === 17) {
    circle.call(force.drag);
    svg.classed('ctrl', true);
  }

  if(!selected_node && !selected_link) return;
  switch(d3.event.keyCode) {
    case 8: // backspace
//    case 46: // delete
//      if(selected_node) {
//        nodes.splice(nodes.indexOf(selected_node), 1);
//        spliceLinksForNode(selected_node);
//      } else if(selected_link) {
//        links.splice(links.indexOf(selected_link), 1);
//      }
//      selected_link = null;
//      selected_node = null;
//      restart();
//      break;
    case 66: // B
      if(selected_link) {
        // set link direction to both left and right
        selected_link.left = true;
        selected_link.right = true;
      }
      restart();
      break;
    case 76: // L
      if(selected_link) {
        // set link direction to left only
        selected_link.left = true;
        selected_link.right = false;
      }
      restart();
      break;
    case 82: // R
      if(selected_node) {
        // toggle node reflexivity
        selected_node.reflexive = !selected_node.reflexive;
      } else if(selected_link) {
        // set link direction to right only
        selected_link.left = false;
        selected_link.right = true;
      }
      restart();
      break;
  }
}

function keyup() {
  lastKeyDown = -1;

  // ctrl
  if(d3.event.keyCode === 17) {
    circle
      .on('mousedown.drag', null)
      .on('touchstart.drag', null);
    svg.classed('ctrl', false);
  }
}

// app starts here
svg.on('mousedown', mousedown)
  .on('mousemove', mousemove)
  .on('mouseup', mouseup);
d3.select(window)
  .on('keydown', keydown)
  .on('keyup', keyup);
//restart();

//GT 颜色与数值对照表
function colors(sign){
	//num=num>20?num%20:parseInt(num);
	for(var i=0;i<labels.length;i++){
		var entity=labels[i];
		if(sign==entity.sign){
			return entity.color;
		}
		if(i==labels.length-1 && sign!=entity.sign){
			return '#ffeeee';
		}
	}
}

function postion(sign){
  for(var i=0;i<labels.length;i++){
      var entity=labels[i];
      if(sign==entity.sign){
        return i;
      }
  }
  return 1;
}

//添加设备
function addnode() {
	//先编辑提交 到数据库添加一条数据得到ID 后显示节点
	var assetNo=d3.select("#nodeAssetNo").property('value');//资产编号
	var name=d3.select("#nodeName").property('value');//资产名称
	var type=d3.select("#nodeType").property('value');//资产类型
	var label=d3.select("#nodeLabel").property('value');//label
	var status=d3.select("#nodeStatus").property('value');//资产状态
	


	$.ajax({
		type: "POST",
		contentType:"application/json; charset=UTF-8",
        url: window.basePath+"/api/cmdb/ci",
        data: JSON.stringify({'name':name,'status':status,'type':type,'label':label,'assetNo':assetNo,props:selected_node.props  }),
        dataType: "json",
        success:function(data){
        	//成功后得到ID
			if(data.status==200){
				var node=data.data.node[0];
				node.x = 634;
				node.y = 265.5625;
				
				nodes.push(node);
				selected_node=node;
				restart();
				hideFeedForm(true);;
			}
			
			},
       error: function(data){jAlert("服务器请求异常",'提示');}
	});
	  
	  
	 
}
//显示节点信息
function shownode(){
	d3.select("#nodeAssetNo").property('value',selected_node.assetNo==undefined?"":selected_node.assetNo);//资产编号
	d3.select("#nodeName").property('value',selected_node.name==undefined?"":selected_node.name);//资产名称
	d3.select("#nodeType").property('value',selected_node.type==undefined?"":selected_node.type);//资产类型
	d3.select("#nodeLabel").property('value',selected_node.label==undefined?"":selected_node.label);//label
	for(var i=0;i<treeNodes.length;i++){
		if(selected_node.label==treeNodes[i].sign){
			d3.select("#citySel").property('value',treeNodes[i].label);
			break;
		}
	}
	d3.select("#nodeStatus").property('value',selected_node.status==undefined?"":selected_node.status);//资产状态
	
	//先移除div中原来的标签
	d3.select('#nodeTab').selectAll('tr').remove('tr');
	
	if(selected_node.label){
		var label=null;
		/*
		//根据选择‘节点’的label 查询label的ID 
	    d3.xhr(window.basePath+"/api/cm/findLabel?sign="+selected_node.label).send("GET", function(error, json) {
	    	if (!error){
	    		label =JSON.parse(json.responseText);
	    		
	    		if(selected_node.props){
	    			var keys=[];
		    		for(var key in selected_node.props){
		    			keys.push(key);
		    		}
		    		
		    		//写入固定属性
		    		for(var i=0;i<params.length;i++){
		    			var p=params[i];
		    			var num=0;
		    			for(var j=0;j<keys.length;j++){
		    				if(p.sourceType==1 && p.sourceId==label.id && p.key==keys[j]){//节点已有属性
		    					num++;
		    					break;
		    				}
		    			}
		    			if(p.sourceType==1 && p.sourceId==label.id && p.fix==1 && num==0){//节点 中没有的固定属性
	                		selected_node['props'][p.key]='';
	                	}
	                	
		    		}
		    		keys=[];
		    		for(var key in selected_node.props){
		    			keys.push(key);
		    		}
		    		
	    			d3.select('#nodeTab').selectAll('tr')
	    			  .data(keys).enter()
	    			  .append('tr')//.nextSibling
	    			  .attr('id',function(d){
	    				  return 'tr'+d;
	    				})
	    			  .html(function(d){//undefined
	    				  var str="";
	    		               if(label!=null){
	    		            	   if(d==""){//新增后props 属性
	   			                		var strS="";
		    			                	
		    			                	strS='<input type="text" id="input'+d+'" value="'+selected_node.props[d]+'" disabled/>'; 
	   			                		str+='<td style="padding-left: 0px;width:145px;"><span id="span'
	   			    						  +d+'" style="width:50px;text-align:right;">未定义:</span><input type="hidden" id="select'+
	   			    						  d+'" style="width: 90px;margin-left: 52px;"/></td>'+ 
	   			    						  '<td style="padding-left: 21px;">'+strS+'</td><td>'
	   			    						  +'<input id="edtBtn'+d+'" name="edtBtn" type="button" style="background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;" onclick="edtBtnClk(\'text\',\''+d+'\',\'未定义\',\'0\')" />'
	   			    						  +'&nbsp;<input type="button" value="" style="background-image:url(css/img/tup/del.jpg);width:22px;height:22px;" onclick=\'delBtnClk("'+d+'")\'/></td>';
	   			                		return str;
	   			                	}
	    		            	  
	    		            	   for(var i=0;i<params.length;i++){
	    			                	var p=params[i];
	    			                	
	    			                	//sourceType==1 类型为节点  key相等 labelId相同
	    			                	if((p.sourceType==1 && d==p.key && p.sourceId==label.id)){//新增加行  动态属性
	    			                		var strS="";
		    			                	if(p.valueType=="date"){
		    			                		 strS='<input id="input'+d+'" placeholder="请输入日期"  style="width: 151px;" class="laydate-icon" onClick="laydate({istime: true, format: \'YYYY-MM-DD hh:mm:ss\'})" value="'
		    			                		 +selected_node.props[d]+'" disabled>';
		    			                	}else{
		    			                		strS='<input type="text" id="input'+d+'" value="'+selected_node.props[d]+'" disabled/>';
		    			                	}
	    			                		if(p.fix==1){//固定属性 不允许编辑显示属性名  不允许删除
	    			                			
		    			    					str+='<td style="padding-left: 0px;width:145px;"><span id="span'
		    			    						  +d+'">'+p.descName+':</span></td>'+
		    			    						  '<td style="padding-left: 21px;">'+
		    			    						  strS+'</td><td>'
		    			    						  +'<input id="edtBtn'+d+'" name="edtBtn" type="button" style="background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;" onclick="edtBtnClk(\''
		    			    						  +p.valueType+'\',\''+d+'\',\''+p.descName+'\',\''+p.fix+'\')" />'
		    			    						  +'&nbsp;</td>';
		    			    					  break;
	    			                		}else{
	    			                			 //类型设置 读取JSON  string date  int float
		    			    					str+='<td style="padding-left: 0px;width:145px;"><span id="span'
		    			    						  +d+'">'+p.descName+':</span><input type="hidden" id="select'+
		    			    						  d+'" style="width: 90px;margin-left: 52px;"/></td>'+
		    			    						  '<td style="padding-left: 21px;">'+
		    			    						  strS+'</td><td>'
		    			    						  +'<input id="edtBtn'+d+'" name="edtBtn" type="button" style="background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;" onclick="edtBtnClk(\''
		    			    						  +p.valueType+'\',\''+d+'\',\''+p.descName+'\',\''+p.fix+'\')" />'
		    			    						  +'&nbsp;<input type="button" value="" style="background-image:url(css/img/tup/del.jpg);width:22px;height:22px;" onclick=\'delBtnClk("'+d+'")\'/></td>';
		    			    					  break;
	    			                		}
	    			                		
	    			                	}
	    			                }
	    		            	   
	    		               }
	    					
	    				  return str;
	    			  });
	    		  }
	    	}else{
	    		jAlert("服务器请求异常!",'提示');
	    	}
	    });
		*/
	}
	
    
	
}



//显示连线信息
//
var openAside = function (model, linkTypes) {
    var modalInstance = $aside.open({
            templateUrl: 'assets/views/system/tpl/asideContent.html',
            placement: 'right',
            size: 'sm',
            backdrop: true,
            controller: function ($scope, $modalInstance, ModelData, optionLinkTypes) {
            	  $scope.modelData = ModelData;
              
            	  $scope.linktypeOptions = optionLinkTypes;
                if($scope.modelData.name!=""){
                  angular.forEach($scope.linktypeOptions,function(item){
                    if(item.type==$scope.modelData.name){
                      $scope.modelData.linkName=item;
                    }
                  })
                }
                $scope.ok = function (e) {
                    $modalInstance.close($scope.modelData);
                    //e.stopPropagation();
                };
                $scope.cancel = function (e) {
                    $modalInstance.dismiss();
                    //e.stopPropagation();
                };
            },
            resolve: {
            	ModelData: function(){
            		return model;
            	},
            	optionLinkTypes: function(){
            		return linkTypes;
            	}
            }
    });
    modalInstance.result.then(function (selectedItem) {
        //TODO create Edge
        console.log(selectedItem);
        if(selectedItem.id==-1){
          api_cmdb.createRef({'id':selectedItem.id,'name':selectedItem.linkName.type,'source':selectedItem.source.id,'target':selectedItem.target.id,'left':selectedItem.left,'right':selectedItem.right}).then(function(response){
             if(response&&response.status==200){
                //model.name=selectedItem.linkName.type;
                var link = response.data.edge[0];
                for (var j = 0; j < nodes.length; j++) {
                    if (link.source == nodes[j].id) {
                        link.source = nodes[j];
                    }
                    if (link.target == nodes[j].id) {
                        link.target = nodes[j];
                    }
                }
                links.push(link);
          //     selected_link.name=linkName;
          //     selected_link.cost=linkCost;
                restart();
             }else{

             }
          })
        }else{
          api_cmdb.putRef({'id':selectedItem.id,'name':selectedItem.linkName.type,'source':selectedItem.source.id,'target':selectedItem.target.id,'left':selectedItem.left,'right':selectedItem.right}, selectedItem.id).then(function(response){
              if(response&&response.status==200){
                //model=selectedItem;
                angular.forEach(links,function(link,index){
                  if(link.name == model.name){
                    links[index]=response.data.edge[0];
                    for (var j = 0; j < nodes.length; j++) {
                        if (links[index].source == nodes[j].id) {
                            links[index].source = nodes[j];
                        }
                        if (links[index].target == nodes[j].id) {
                            links[index].target = nodes[j];
                        }
                    }
                  }
                })

                restart();
              }else{

              }
          })
        }
        
    }, function () {
        //console.log('Modal dismissed at: ' + new Date());
    });
};
//
//
function showLink(){

	var linkeName = $scope.linkName = selected_link.name==undefined?"":selected_link.name;
	$scope.linkCost = selected_link.cost==undefined?"":selected_link.cost;


	// d3.select("#linkName").property('value',selected_link.name==undefined?"":selected_link.name);
	// d3.select("#linkCost").property('value',selected_link.cost==undefined?"":selected_link.cost);
	
	//var linkeName=d3.select("#linkName").property('value');
	//先移除div中原来的标签
	d3.select('#linkTab').selectAll('tr').remove('tr');
	
	var linkId;
	//sourceTYpe=2 and sourceId=连线nameId
	//当前选择的连线name Id
	for(var i=0;i<linkType.length;i++){
		if(linkeName==linkType[i].type){
			linkId=linkType[i].id;
		}
	}
	var props=selected_link.props;
	var keys=[];
	for(var key in props){
		keys.push(key);
	}
	// //写入固定属性
	// for(var i=0;i<params.length;i++){
	// 	var p=params[i];
	// 	var num=0;
	// 	for(var j=0;j<keys.length;j++){
	// 		if(p.sourceType==2 && p.sourceId==linkId && p.key==keys[j]){//连线已有属性
	// 			num++;
	// 			break;
	// 		}
	// 	}
	// 	if(p.sourceType==2 && p.sourceId==linkId && p.fix==1 && num==0){//连线 中没有的固定属性
 //    		selected_link['props'][p.key]='';
 //    	}
    	
	// }
	keys=[];
	for(var key in selected_link.props){
		keys.push(key);
	}

	if(keys){
		d3.select('#linkTab').selectAll('tr')
		  .data(keys).enter()
		  .append('tr')//.nextSibling
		  .attr('id',function(d){
				 return 'trLink'+d;
			}).html(function(d){
				  var str="";
				  if(d==""){//新增后props 属性
		            	var strS="";
	                
	                	strS='<input type="text" id="inputLink'+d+'" value="'+props[d]+'" disabled/>';
		                str+='<td style="padding-left: 0px;width:145px;"><span id="spanLink'
		    					+d+'" style="width:50px;text-align:right;">未定义:</span><input type="hidden" id="selectLink'+
		    					d+'" style="width: 90px;margin-left: 52px;"/></td>'+
		    					'<td style="padding-left: 21px;">'+//111111111111111111111 padding-left: 60px;
		    					strS +'</td><td>'
		    					+'<input id="edtBtnLink'+d+'" type="button" name="edtBtn" style="background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;" onclick="edtBtnLinkClk(\'text\',\''
		    					+d+'\',\'未定义\',\'0\')" />'
		    					+'&nbsp;<input type="button" value="" style="background-image:url(css/img/tup/del.jpg);width:22px;height:22px;" onclick=\'delBtnLinkClk("'+d+'")\'/></td>';
		    				return str;
		              }
				  
	    			for(var j=0;j<params.length;j++){
  			            var p=params[j];
		    			if((p.sourceType==2 && d==p.key && p.sourceId==linkId)){//新增加行
		    				var strS="";
		                	if(p.valueType=="date"){
		                		 strS='<input id="inputLink'+d+'" placeholder="请输入日期" style="width: 151px;" class="laydate-icon" onClick="laydate({istime: true, format: \'YYYY-MM-DD hh:mm:ss\'})" value="'+props[d]+'" disabled>';
		                	}else{
		                		strS='<input type="text" id="inputLink'+d+'" value="'+props[d]+'" disabled/>';
		                		
		                	}
		                	if(p.fix==1){//固定属性 不允许编辑显示属性名  不允许删除
		                		 //类型设置 读取JSON  string date  int float   22222222222222222padding-left: 21px;
				    			str+='<td style="width:145px;"><span id="spanLink'+d+'">'+p.descName+':</span></td>'+
				    					'<td style="padding-left: 21px;">'+strS+'</td><td>'+'<input id="edtBtnLink'+d
				    					+'" type="button" name="edtBtn" style="background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;" onclick="edtBtnLinkClk(\''
				    					+p.valueType+'\',\''+d+'\',\''+p.descName+'\',\''+p.fix+'\')" />'
				    					+'&nbsp;</td>';
				    			break;
	                		}else{
	                			 //类型设置 读取JSON  string date  int float
				    			str+='<td style="width:145px;"><span id="spanLink'
				    					+d+'">'+p.descName+':</span><input type="hidden" id="selectLink'+
				    					d+'" style="width: 90px;margin-left: 52px;"/></td>'+
				    					'<td style="padding-left: 21px;">'+//333333333333333 padding-left: 21px;
				    					strS
				    					+'</td><td>'
				    					+'<input id="edtBtnLink'+d+'" type="button" name="edtBtn" style="background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;" onclick="edtBtnLinkClk(\''
				    					+p.valueType+'\',\''+d+'\',\''+p.descName+'\',\''+p.fix+'\')" />'
				    					+'&nbsp;<input type="button" value="" style="background-image:url(css/img/tup/del.jpg);width:22px;height:22px;" onclick=\'delBtnLinkClk("'+d+'")\'/></td>';
				    			break;
	                		}
		                	
			                		
			            }
	    			}
				  return str;
			  });
	}

	hideLinkForm(false);
}

//删除（修改状态为报废）
function delnode_update(){
	if(selected_node || selected_link){
		jConfirm('确定删除?', '提示', function(r) {
			if(r){
				if(selected_node){//删除配置
					//节点ID（节点删除执行成功，数据库节点未删除 ，删除节点关系时执行失败）
					var id=selected_node.id;
					var name=selected_node.name;
					var type=selected_node.type;//资产类型
					var label=selected_node.label;	//资产类型				
					var assetNo=selected_node.assetNo;//资产编号					
					var props =selected_node.props;
					var status=CMConstants.DISCARDE;
					//删除后，状态变为废弃 
				    $.ajax({
				    		type: "PUT",
				    		contentType:"application/json; charset=UTF-8",
				    	    url: window.basePath+"/api/cmdb/ci/"+id,
				    	    data: JSON.stringify({'id':id,'name':name,'status':status,'type':type,'label':label,'assetNo':assetNo,'props':props}),
				    	    dataType: "json",
				    	    success:function(data){
				    			if(data.status==200){	
				    			
				    				jAlert("删除成功!",'提示');	
				    			
				    				selected_node.type=type;//资产类型
				    				selected_node.status=status;
				    				selected_node.label=label;		//资产类型				
				    				selected_node.assetNo=assetNo;  //资产编号					
				    				selected_node.props=props;
				    				selected_node.name=name;

				    				restart();
				    				query(label,""); 				
				    				//shownode();
				    			}
				    				
				    		},
				    	    error: function(data){jAlert("服务器请求异常",'提示');}
				          });
												
				    	}
							
					}else{
							jAlert("请求异常",'提示');
					}
			
				});
					
			}else{
				jAlert('请先选择删除项!','提示');
			}
			
  }

//删除
function delnode(){
	if(selected_node || selected_link){
		jConfirm('确定删除?', '提示', function(r) {
			if(r){
				if(selected_node){//删除配置
					//节点ID（节点删除执行成功，数据库节点未删除 ，删除节点关系时执行失败）
					var id=selected_node.id;					
					//先删除节点关系
					d3.xhr(window.basePath+"/api/cmdb/ci/"+id+"/refs").send("DELETE", function(error, json) {
						if (!error){
							if(json.status==200){
								var edge=JSON.parse(json.responseText).data.edge;
								for(var i=0;i<edge.length;i++){
									for(var j=0;j<links.length;j++){
										if(edge[i].id==links[j].id){
											links.splice(j, 1);
											break;
										}
									}
									
								}
								//再删除节点
							d3.xhr(window.basePath+"/api/cmdb/ci/"+id).send("DELETE", function(error, json) {
										if (!error){
											if(json.status==200){
												//删除节点
												nodes.splice(nodes.indexOf(selected_node), 1);
												jAlert("删除成功!",'提示');
												hideFeedForm(true);;
											}
											restart();
										}else{
											jAlert("请求异常",'提示');
										}
									});
							}
							
					

						}else{
							jAlert("请求异常",'提示');
						}
						});
				
					
					
				}
				//用户删除关系
				if(selected_link){
					//得到关系ID 删除关系
					var id=selected_link.id;
					d3.xhr(window.basePath+"/api/cmdb/edge/"+id).send("DELETE", function(error, json) {
						if (!error){
							links.splice(links.indexOf(selected_link), 1);
							jAlert("删除成功!",'提示');
							hideLinkForm(true);
							restart();
						}else{
							jAlert("请求异常",'提示');
						}
						});
				}
			}
			
		});
	}else{
		jAlert('请先选择删除项!','提示');
	}
	

}

var CI ={};
CI.add = addnode;
window.CI = CI;
d3.select("#traversal").selectAll('a').data([{name:'遍历',id:'traversalBtn'}]).enter()
.append('a')
      .html(function (d) { return d.name; })
      .on('click', function (d) {
        if(d.id=="traversalBtn"){
          if(selected_node == null){
            alert("没有选择节点。。。");
          }else{
            $.ajax({
         type: "GET",
             url: window.basePath+"/api/cmdb/traversal/"+selected_node.assetNo,
             dataType: "json",
             success:function(json){
               var d=json.data;
               var node=d.node;
               var link=d.edge;
               var tempNode=[];
               var tempLink=[];
              //nodes 或者links 要去重
               for(var i=0;i<node.length;i++){
                 var tmp=0;
                 for(var j=0;j<nodes.length;j++){
                   if(node[i].id==nodes[j].id){
                     tmp++;
                     break;
                   }
                 }
                 if(tmp==0){
                tempNode.push(node[i]);
                 }
               }
               
               for(var i=0;i<link.length;i++){
                var tmp=0;
                 for(var j=0;j<links.length;j++){
                   if(link[i].id==links[j].id){
                    tmp++;
                     break;
                   }
                 }
                if(tmp==0){
                tempLink.push(link[i]);
                }
               }
               //数据写入页面
               for(var i=0;i<tempNode.length;i++){//nodes  不清空
                 nodes.push(tempNode[i]); 
               }
              for(var i=0;i<tempLink.length;i++){//link  不清空
               links.push(tempLink[i]); 
              }
              //links转换
              for(var i=0;i<links.length;i++){
                for(var j=0;j<nodes.length;j++){
                  if(links[i].source==nodes[j].id){
                    links[i].source=nodes[j];
                  }
                  if(links[i].target==nodes[j].id){
                    links[i].target=nodes[j];
                  }
                }
              }
              
               restart();
             },
             error:function(){alert("访问服务器出错!");}
       });



          }
        }
      });

d3.select("#layout").selectAll('a').data([{name:'布局',id:'layoutBtn'}]).enter()
.append('a')
      .html(function (d) { return d.name; })
      .on('click', function (d) {
        if(d.id=="layoutBtn"){
          var k = Math.sqrt(nodes.length / (width * height));
          //var len = labels.length;
          // nodes.forEach(function(o, i) {
          //    //console.log( "postion:" + postion(o.label) % len);
          //    o.x += postion(o.label) & 1 ? 140 : -140;
          //    o.y += postion(o.label) & 2 ? 140 : -140;
          //    console.log("[" +o.id + "-" + o.name + "]:" + o.label + "(" + o.x + "," + o.y + ");");
          // });
          force.charge((-10/k)*1.5);
          force.gravity(100*k);
          force.resume();
        }
      });


//添加node 点击事件
d3.select("#addsss").selectAll('a').data([{name:'添加',id:'addBtn'}]).enter()
.append('a')
      .html(function (d) { return d.name; })
      .on('click', function (d) {
    	  if(d.id=="addBtn"){
    		selected_node={id:-1};
    		
    		//内容置空
    		d3.select("#nodeAssetNo").property('value','');//资产编号
    		d3.select("#nodeName").property('value','');//资产名称
    		d3.select("#nodeType").property('value','');//资产类型
    		d3.select("#nodeLabel").property('value','');//label
    		d3.select("#nodeStatus").property('value','');//资产状态
    		d3.select('#nodeTab').selectAll('tr').remove();
    		
    		show("feedbox");return false;
    	  }
      });

//删除
d3.select("#delsss").selectAll('a').data([{name:'删除',id:'delBtn'}]).enter()
.append('a')
      .html(function (d) { return d.name; })
      .on('click', function (d) {
    	  if(d.id=="delBtn"){
    		//delnode();
    		 delnode_update();
    	  }
      });



//修改
d3.select("#uppsss").selectAll('a').data([{name:'修改',id:'edtBtn'}]).enter()
.append('a')
      .html(function (d) { return d.name; })
      .on('click', function (d) {
    	  if(d.id=="edtBtn"){
    		  if(selected_node!=null){
    			  show("feedbox");
    			  return false;
    		  }else{
    			  jAlert("请选择设备",'提示');
    		  }
    	  }
 });

//节点提交
d3.select("#subBtn").on('click',function(d){
	var assetNo=d3.select("#nodeAssetNo").property('value');//资产编号
	var label=d3.select("#nodeLabel").property('value');//label
	
	var props =selected_node.props;
	for(var key in props){
		if(key==""){
			jAlert("您有未定义属性,请删除或编辑!",'提示');
			return;
		}
	}
	if(assetNo==""){
		jAlert("请输入资产编号!",'提示');
		return;
	}else if(label==null ||label==""){
		jAlert("请选择资产类型!",'提示');
		return;
	}else{
		//添加或者更新
		if(selected_node.id==-1){//添加
			addnode();
		}else{//更新
			var idVal=selected_node.id;
		    var name=d3.select("#nodeName").property('value');//资产名称
		    var type=d3.select("#nodeType").property('value');//资产类型
		   
		    var status=d3.select("#nodeStatus").property('value');//资产状态
		  //节点提交 
		    $.ajax({
		    		type: "PUT",
		    		contentType:"application/json; charset=UTF-8",
		    	    url: window.basePath+"/api/cmdb/ci/"+idVal,
		    	    data: JSON.stringify({'id':idVal,'name':name,'status':status,'type':type,'label':label,'assetNo':assetNo,'props':selected_node.props  }),
		    	    dataType: "json",
		    	    success:function(data){
		    			if(data.status==200){
		    				jAlert("更新成功!",'提示');
		    				selected_node.assetNo=assetNo;
		    				selected_node.name=name;
		    				selected_node.type=type;
		    				selected_node.label=label;
		    				selected_node.status=status;
		    				
		    				restart();
		    				//shownode();
		    			}
		    				
		    		},
		    	    error: function(data){jAlert("服务器请求异常",'提示');}
		    });

		}
		//  restart();
	}
	
});

//连线提交
d3.select("#subBtn1").on('click',function(d){
	var linkName=d3.select("#linkName").property('value');
	var linkCost=d3.select("#linkCost").property('value');
	var idVal=selected_link.id;
	
	var props =selected_link.props;
	for(var key in props){
		if(key==""){
			jAlert("您有未定义属性,请删除或编辑!",'提示');
			return;
		}
	}
	
	if(idVal==-1){//添加 
		selected_link.name=linkName;
		//selected_link.status=linkStatus;
		selected_link.cost=linkCost;
		var l=selected_link;
		 $.ajax({
	    		type: "POST",
	    		contentType:"application/json; charset=UTF-8",
	    	    url: window.basePath+"/api/cmdb/edge",
	    	    data: JSON.stringify({'id':l.id,'name':l.name,'status':l.status,'cost':l.cost,'left':l.left,'right':l.right,'source':l.source.id,'target':l.target.id,'props':l.props}),
	    	    dataType: "json",
	    	    success:function(data){
	    			if(data.status==200){
	    				var link=data.data.edge[0];
	    				jAlert("添加成功!",'提示');
	    				selected_link.id=link.id;
	    				
	    				restart();
	    				hideLinkForm(true);
	    			}
	    				
	    		},
	    	    error: function(data){jAlert("服务器请求异常",'提示');}
	    });
	}else{
		// 连线提交
	    $.ajax({
	    		type: "PUT",
	    		contentType:"application/json; charset=UTF-8",
	    	    url: window.basePath+"/api/cmdb/edge/"+idVal,
	    	    data: JSON.stringify({'id':idVal,'name':linkName,'cost':linkCost,'props':selected_link.props  }),
	    	    dataType: "json",
	    	    success:function(data){
	    			if(data.status==200){
	    				jAlert("更新成功!",'提示');
	    				
	    				selected_link.name=linkName;
	    				//selected_link.status=linkStatus;
	    				selected_link.cost=linkCost;
	    				
	    				restart();
	    				showLink();
	    			}
	    				
	    		},
	    	    error: function(data){jAlert("服务器请求异常",'提示');}
	    });
	}
// restart();
	
});

//全局变量 正在编辑的属性ID
var etdBtnId="";
//编辑按钮点击事件
function edtBtnClk(type,etdId,value,fix){
	var v=d3.select('#edtBtn'+etdId).property('name');

	if(v=='edtBtn'){
		d3.select('#input'+etdId).property('disabled','');//可编辑
		if(type=="date"){//加载日期
			
			//$("#input"+etdId).datepicker({dateFormat: 'yy-mm-dd'});$.datepicker.regional[ "zh-cn" ];
		}else if(type=='int'){//只能为整型
			d3.select('#input'+etdId).on('keyup',function(){
				this.value=	this.value.replace(/[^\d]/g, '');
			});
		}else if(type=='float'){
			d3.select('#input'+etdId).on('keyup',function(){
				this.value=	this.value.replace(/[^\d.]/g,'');
			});
		}
		//span文字隐藏  select2显示
	  //   d3.select('.addtd').classed('addtds');
		if(fix==0){//动态属性  显示名称隐藏
			d3.select('#span'+etdId).attr('style','display:none');
		}
		 
	     //d3.select('tr#tr'+etdId + 'td + td').attr('style','padding-left:0px;');
		 
		//$('#select'+etdId).select2({ multiple: true, data:selectData});//分号选择
		 //根据用户选择的label 和节点类型查询
		 var t=d3.select('#nodeLabel').property('value');
		 var typeId="";//选中的资源label的ID
		 for(var i=0;i<labels.length;i++){
			 if(labels[i].sign==t){
				 typeId=labels[i].id;
				 break;
			 }
		 }
		 var res=[];
		
		 //改变属性
		d3.select('#edtBtn'+etdId).property('name','edt');
		d3.select('#edtBtn'+etdId).attr('style','background-image:url(css/img/tup/queding.jpg);width:22px;height:22px;');
		
		 $('#select'+etdId).select2({
			 	ajax: {
			        url: window.basePath+'/api/cm/findByPro',//sourceType=1 节点 
			        type:'GET',
			        dataType: 'json',
			        data: function(){
			        	return {
			        		sourceType : 1,
			        		sourceId: typeId
			        	};
			        },
			        results: function (data) {
			        	res=data;
			        	
			            var bindData = [];
			        	for(var i = 0;i < data.length;i++){
			            	bindData.push({'id':data[i].key,'text':data[i].descName});
			            } 
			        	
			        	return {results: bindData};
			        }
			    },
			 createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} },
			    //multiple: true,//单选 or 多选
			    
		 }).on("select2-selecting", function(e) {
			
			 etdBtnId=this.id.substr('select'.length);
			 	var result = [];
	        	for(var i = 0;i < res.length;i++){
	        		result.push({'id':res[i].key,'text':res[i].descName});
	            }
	        	
	        	if(result.length==0){
	        		//置空
					d3.select("#proType").property('value','');
					d3.select("#proNo").property('value','');
					
					d3.select('#overlay').style('display','block');
					d3.select('#win').style('display','block');
					return;
	        	}
			 for(var i=0;i<result.length;i++){
				 if(e.choice.id==result[i].id && e.choice.text==result[i].text){//用户选择的是已有的属性
					 //写入nodes
					 var props=selected_node.props;
					 // 用户选择不能重复
					 for(var key in props){
						if(e.val==key && e.val!=etdId){
							jAlert("此配置已有此属性,请另外选择!",'提示',function(){
								$('#select'+etdId).select2('data', {id:etdId,text:value});
								
							});
							return;
						}
					 }
					 //用户选择验证通通过  写入到nodes中
						for(var p in props){
							 if(p==etdId){
								 var text=props[p];
								 delete props[p];
								 selected_node.props[e.choice.id]=text;
								 shownode();//此处不重新加载(shownode) 会有问题
								 return;
							 }
						 }
					 
				 }else if((i==result.length-1) && (e.choice!=result[i])){//用户新输入的
					 
					//置空
						d3.select("#proType").property('value','');
						d3.select("#proNo").property('value','');
						
						d3.select('#overlay').style('display','block');
						d3.select('#win').style('display','block');
						return;
				 }
			 }
		});
		//绑定默认值
		$('#select'+etdId).select2('data', {id:etdId,text:value});
	}else{//确定
		d3.select('#edtBtn'+etdId).property('name','edtBtn');
		d3.select('#edtBtn'+etdId).attr('style','background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;');
		
		//数据写入nodes
		var props=selected_node.props;
		for(var key in props){
			if(key==etdId){
				var text=d3.select('#input'+etdId).property('value');
				var k=null;
				if(fix==0){
					k=d3.select('#select'+etdId).property('value');
				}else{
					k=etdId;
				}
				delete props[etdId];
				props[k]=text;
				shownode();
				return;
			}
		}
	}
}
//编辑按钮点击事件
function edtBtnLinkClk(type,etdId,value,fix){
	var linkeName=d3.select('#linkName').property('value');
	if(linkeName==""){
		jAlert("请先选取连线名称!",'提示');
		return;
	}
	var v=d3.select('#edtBtnLink'+etdId).property('name');
	
	if(type=="date"){//加载日期
	//	$("#inputLink"+etdId).datepicker({dateFormat: 'yy-mm-dd'});$.datepicker.regional[ "zh-cn" ];
	}else if(type=='int'){//只能为整型
		d3.select('#inputLink'+etdId).on('keyup',function(){
			this.value=	this.value.replace(/[^\d]/g, '');
		});
	}else if(type=='float'){
		d3.select('#inputLink'+etdId).on('keyup',function(){
			this.value=	this.value.replace(/[^\d.]/g,'');
		});
	}
	
	if(v=='edtBtn'){
		d3.select('#inputLink'+etdId).property('disabled','');//可编辑
		//改变属性
		d3.select('#edtBtnLink'+etdId).attr('style','background-image:url(css/img/tup/queding.jpg);width:22px;height:22px;');
		d3.select('#edtBtnLink'+etdId).property('name','edt');
		if(fix==0){//动态属性隐藏 
			//span文字隐藏  select2显示
			 d3.select('#spanLink'+etdId).attr('style','display:none');
		}
		
		
		 //根据用户选择的name（连线名称） 查询
		
		 var linkId;//选中的name的ID 即属性表里的sourceId
		 for(var i=0;i<linkType.length;i++){
				if(linkeName==linkType[i].type){
					linkId=linkType[i].id;
				}
			}
		 var res=[];
		 $('#selectLink'+etdId).select2({
			 	ajax: {
			        url: window.basePath+'/api/cm/findByPro',//sourceType=2 连线 
			        type:'GET',
			        dataType: 'json',
			        data: function(){
			        	return {
			        		sourceType : 2,
			        		sourceId: linkId
			        	};
			        },
			        results: function (data) {
			        	res=data;
			        	
			            var bindData = [];
			        	for(var i = 0;i < data.length;i++){
			            	bindData.push({'id':data[i].key,'text':data[i].descName});
			            } 
			        	
			        	return {results: bindData};
			        }
			    },
			 createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.text.localeCompare(term)===0; }).length===0) {return {id:term, text:term};} },
			    
		 }).on("select2-selecting", function(e) {
			 
			 etdBtnId=this.id.substr('selectLink'.length);
			 	var result = [];
	        	for(var i = 0;i < res.length;i++){
	        		result.push({'id':res[i].key,'text':res[i].descName});
	            }
	        	
	        	if(result.length==0){//如果没有属性  弹出添加属性框
	        		//置空
					d3.select("#proType").property('value','');
					d3.select("#proNo").property('value','');
					
					d3.select('#overlay').style('display','block');
					d3.select('#win').style('display','block');
					return;
	        	}
	        
			 //console.log ("selecting val="+ e.val+" choice="+ JSON.stringify(e.choice));
			 for(var i=0;i<result.length;i++){
				 if(e.choice.id==result[i].id && e.choice.text==result[i].text){//用户选择的是已有的属性
					 //nodes props
					 var props=selected_link.props;
					 // 用户选择不能重复
					 for(var key in props){
						if(e.val==key && e.val!=etdId){
							
							jAlert("此配置已有此属性,请另外选择!",'提示',function(){
								//绑定默认值
								$('#selectLink'+etdId).select2('data', {id:etdId,text:value});
							});
							
							return;
						}
					}
					 //用户选择验证通过  写入到nodes中
					for(var p in props){
						if(p==etdId){
							delete props[etdId];
							selected_link.props[e.choice.id]=e.choice.text;
								 
							showLink();//此处不重新加载(shownode) 会有问题
							return;
						}
					}
					 
				 }else if((i==result.length-1) && (e.choice!=result[i])){//用户新输入的
					 
					//置空
						d3.select("#proType").property('value','');
						d3.select("#proNo").property('value','');
						
						d3.select('#overlay').style('display','block');
						d3.select('#win').style('display','block');
						return;
				 }
			 }
		});;
		
		//绑定默认值
		$('#selectLink'+etdId).select2('data', {id:etdId,text:value});
		
	}else{//确定
		d3.select('#edtBtnLink'+etdId).property('name','edtBtn');
		d3.select('#edtBtnLink'+etdId).attr('style','background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;');
		//数据写入links
		var props=selected_link.props;
		for(var key in props){
			if(key==etdId){
				var k=null;
				var text=d3.select('#inputLink'+etdId).property('value');
				if(k==0){
					k=d3.select('#selectLink'+etdId).property('value');
				}else{
					k=etdId;
				}
				
				delete props[etdId];
				props[k]=text;

				showLink();
				return;
			}
		}
		showLink();
	}
}
//节点属性删除按钮点击事件
function delBtnClk(delId){
	jConfirm('确定删除?', '提示', function(r) {
		if(r){
			//提交的时候只删除数据，不删除属性表数据
			//删除表格
			d3.select('#tr'+delId).selectAll('td').remove('td');
			//删除node属性
			var props=selected_node.props;
			for(var key in props){
				if(delId==key){
					delete props[key];//删除node中元素 
					return;
				}
			}
		}
	});
	
}
//连线属性删除按钮点击事件
function delBtnLinkClk(delId){
	jConfirm('确定删除?', '提示', function(r) {
		//提交的时候只删除数据，不删除属性表数据
		if(r){
			//删除表格
			d3.select('#trLink'+delId).selectAll('td').remove('td');
			//删除node属性
			var props=selected_link.props;
			for(var key in props){
				if(delId==key){
					delete props[delId];//删除link中元素 
					return;
				}
			}
		}
	});

}

//连线名 的选择事件 选择后将 值写入到 selected_node
d3.select('#linkName').on('change',function(){
	var num=0;
	for(var key in selected_link.props){
		num++;
		break;
	}
	var tType=this;
	if(num>0){
		jConfirm('更换名称选项,动态属性将会被删除，是否继续？', '提示', function(r) {
			if(r){
				selected_link.name=tType.value;
				selected_link.props={};
				showLink();
				
				selected_link['props']={};
				fixPro(tType.value);
			}else{
				tType.value=selected_link.name;
				return;
			}
		});
		
		
	}else{
		selected_link.name=tType.value;
		selected_link['props']={};
		fixPro(tType.value);
	}
});
//加载固定属性(节点/连线)
function fixPro(label){
	if(selected_node){//操作节点
		var labelId=null;
		//根据选择‘节点’的label 查询label的ID 
		d3.xhr(window.basePath+"/api/cm/findLabel?sign="+label).send("GET", 
			function(error, json) {
		    if (!error){
		    	labelId =JSON.parse(json.responseText).id;
		    	 $.ajax({
					 type: "GET",
			         url: window.basePath+"/api/cm/findByPro",
			         data: {sourceType : 1,sourceId: labelId},
			         dataType: "json",
			         success:function(data){
			        	 
			        	  var keys=[];
				        	for(var i = 0;i < data.length;i++){
				        		var entity=data[i];
				        		if(entity.fix==1){
				        			var key=entity.key;
				        			keys.push(key);
	 			        			selected_node['props'][key]='';
				        		}
				            }
				        //先移除div中原来的标签
				        d3.select('#nodeTab').selectAll('tr').remove('tr');
				          d3.select('#nodeTab').selectAll('tr')
				    	    		.data(keys).enter()
				    	    		.append('tr')
				    	    		.attr('id',function(d){
				    	    			return 'tr'+d;
				    	    	})
				    	    	.html(function(d){ //undefined
				    	    		var str="";
				    				//新增加行  
			    			         var strS="";
			    			         for(var i = 0;i < data.length;i++){
			 			        		var entity=data[i];
			 			        		if(entity.fix==1 && entity.key==d){//固态属性  并且key相等
			 			        			
			 			        			if(entity.valueType=="date"){
					    			             strS='<input id="input'+d+'" placeholder="请输入日期"  style="width: 151px;" class="laydate-icon" onClick="laydate({istime: true, format: \'YYYY-MM-DD hh:mm:ss\'})" value="'
					    			             +'" disabled>';
						    			       }else{
						    			             strS='<input type="text"	 id="input'+d+'" value="" disabled/>';
						    			       }
				    			          //类型设置 读取JSON  string date  int float
				    			    	str+='<td style="padding-left: 0px;width:145px;"><span id="span'
				    			    		+d+'">'+entity.descName+':</span></td>'+
				    			    		'<td style="padding-left: 21px;">'+strS+'</td><td>'+'<input id="edtBtn'+d
				    			    		+'" name="edtBtn" type="button" style="background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;" onclick="edtBtnClk(\''
				    			    		+entity.valueType+'\',\''+d+'\',\''+entity.descName+'\',\''+entity.fix+'\')" />'+'&nbsp;</td>';
				    			    	break;
			 			        		}
			 			            } 
				    			    
				    	    		return str;
				    	    		
				    	    	});
			         },
			         error:function(data){jAlert("服务器访问异常!",'提示');}
				 });
		    }
		});    	
	}else if(selected_link){//操作连线
		var sourceId=null;
		for(var i=0;i<linkType.length;i++){
			if(label==linkType[i].type){
				sourceId=linkType[i].id;
			}
		}
		if(sourceId!=null){
			$.ajax({
				type: "GET",
			    url: window.basePath+"/api/cm/findByPro",
			    data: {sourceType : 2,sourceId: sourceId},
			    dataType: "json",
			    success:function(data){
			        	 
			        var keys=[];
				    for(var i = 0;i < data.length;i++){
				        var entity=data[i];
				        if(entity.fix==1){
				        	var key=entity.key;
				        	keys.push(key);
	 			        	selected_link['props'][key]='';
				        	}
				       }
				     //先移除div中原来的标签
				     d3.select('#linkTab').selectAll('tr').remove('tr');
				     d3.select('#linkTab').selectAll('tr')
				     	.data(keys).enter()
				    	.append('tr')
				    	.attr('id',function(d){
				    	    return 'tr'+d;
				    	})
				    	.html(function(d){ //undefined
				    	    var str="";
				    		//固态属性
			    			 var strS="";
			    			 for(var i = 0;i < data.length;i++){
			 			        	var entity=data[i];
			 			        	if(entity.fix==1 && entity.key==d){//固态属性  并且key相等
			 			        		if(entity.valueType=="date"){
			 			        			strS='<input id="inputLink'+d+'" placeholder="请输入日期" style="width: 151px;" class="laydate-icon" onClick="laydate({istime: true, format: \'YYYY-MM-DD hh:mm:ss\'})" value="" disabled>';
						    			  }else{
						    				  strS='<input type="text" id="inputLink'+d+'" value="" disabled/>';
						    			  }
				    			          //类型设置 读取JSON  string date  int float
				    			    	
					    			    str+='<td style="padding-left: 0px;width:145px;"><span id="spanLink'+d+'">'+entity.descName+':</span></td>'+
					    					'<td style="padding-left: 21px;">'+strS+'</td><td>'+'<input id="edtBtnLink'+d
					    					+'" type="button" name="edtBtn" style="background-image:url(css/img/tup/xiug.jpg);width:22px;height:22px;" onclick="edtBtnLinkClk(\''
					    					+entity.valueType+'\',\''+d+'\',\''+entity.descName+'\',\''+entity.fix+'\')" />'
					    					+'&nbsp;</td>';
					    			    	break;
			 			        		}
			 			            } 
				    	    		return str;
				    	    		
				    	   });
			         },
			         error:function(data){jAlert("服务器访问异常!",'提示');}
				 });
		}
	}
				  
}

//节点'添加属性' 点击事件
d3.select('#addBtn').on('click',function(){
	var label=d3.select('#nodeLabel').property('value');
	
	if(""!=label){
		addRow();
	}else{
		jAlert('请先选择资产类型!','提示');
	}
	
});
//添加属性行
function addRow(){
	if(selected_node.props){
		
		selected_node.props['']='未定义';
	}else{
		
		selected_node['props']={'':'未定义'};
	}
	//用户写入的记录下来
	updJson();
	
	shownode();
}
//刷新时记录用户输入
function updJson(){
	if(selected_node){
		selected_node.assetNo=d3.select("#nodeAssetNo").property('value');
		selected_node.name=d3.select("#nodeName").property('value');
		selected_node.type=d3.select("#nodeType").property('value');
		selected_node.label=d3.select("#nodeLabel").property('value');
		selected_node.status=d3.select("#nodeStatus").property('value');
	}else if(selected_link){
		selected_link.name=d3.select("#linkName").property('value');
		selected_link.cost=d3.select("#linkCost").property('value');
	}
}

//=============弹出层添加属性begin=======================================
//加载属性类型
d3.select('#proType').selectAll('option')
.data(proTypes).enter()
.append('option')
.attr('value',function(d){return d.key;})
.html(function(d){ return d.value;});
//提交
d3.select('#addSubBtn').on('click',function(){
	if(selected_node){
		var proType=d3.select("#proType").property('value');
		var proNo=d3.select("#proNo").property('value');
		var desName=d3.select("#select"+etdBtnId).property('value');//正在编辑select2的值

		//插入前先查询节点‘英文编号’的此label 此简称是否存在
		var t=d3.select('#nodeLabel').property('value');
		var labelId="";//选中的资源label的ID
		 for(var i=0;i<labels.length;i++){
			 if(labels[i].sign==t){
				 labelId=labels[i].id;
				 break;
			 }
		 }
		 $.ajax({
			 type: "GET",
	         url: window.basePath+"/api/cm/findByPros",
	         data: {sourceType : 1,sourceId: labelId,keyname:proNo},
	         dataType: "text",
	         success:function(data){
	        	 if(data==0){//数据库中没有此属性  允许插入
	        		//插入操作 返回实体
	        		$.ajax({
	        			 type: "POST",
	        			 contentType:"application/json; charset=UTF-8",
	        	         url: window.basePath+"/api/cm/dynparam",
	        	         data: JSON.stringify({ descName:desName, key:proNo, sourceId:labelId, sourceType:1, valueType:proType,fix:0}),//JSON.stringify(entity),fix:0动态属性
	        	         dataType: "json",
	        	         success:function(data){
	        	        	 //插入成功后改变正在编辑的
	     					var props=selected_node.props;
	     						for(var key in props){
	     							if(key==etdBtnId){
	     								delete props[key];
	     								props[proNo]=desName;
	     								
	     								//层隐藏
	     				        		d3.select('#overlay').style('display','none');
	     				        		d3.select('#win').style('display','none');
	     				        		//更新属性  
	     				        		initParams();
	     								restart();
	     								return;
	     							}
	     						}
	     					
	     					},
	        	         error: function(data){jAlert("服务器请求异常",'提示');}
	        		});
	        		
	        	 }else{
	        		 jAlert("此属性编号已存在,请重新输入编号!",'提示');
	        	 }
	         },
	         error:function(data){jAlert("服务器访问异常!",'提示');}
		 });
	}else if(selected_link){
		var proType=d3.select("#proType").property('value');
		var proNo=d3.select("#proNo").property('value');
		var desName=d3.select("#selectLink"+etdBtnId).property('value');//正在编辑select2的值
		
		//插入前先查询节点‘英文编号’的此label 此简称是否存在
		
		 var linkeName=d3.select('#linkName').property('value');
		 var linkId;//选中的name的ID 即属性表里的sourceId
		 for(var i=0;i<linkType.length;i++){
			if(linkeName==linkType[i].type){
				linkId=linkType[i].id;
			}
		}
		 $.ajax({
			 type: "GET",
	         url: window.basePath+"/api/cm/findByPros",
	         data: {sourceType : 2,sourceId: linkId,keyname:proNo},
	         dataType: "text",
	         success:function(data){
	        	 if(data==0){//数据库中没有此属性  允许插入
	        		//插入操作 返回实体
	        		$.ajax({
	        			 type: "POST",
	        			 contentType:"application/json; charset=UTF-8",
	        	         url: window.basePath+"/api/cm/dynparam",
	        	         data: JSON.stringify({ descName:desName, key:proNo, sourceId:linkId, sourceType:2, valueType:proType,fix:0}),//JSON.stringify(entity),
	        	         dataType: "json",
	        	         success:function(data){
	        	        	 //插入成功后改变正在编辑的
	        	        	 //params=JSON.parse(json.responseText);
	     					var props=selected_link.props;
	     						for(var key in props){
	     							if(key==etdBtnId){
	     								delete props[key];
	     								props[proNo]=desName;
	     								//层隐藏
	     				        		d3.select('#overlay').style('display','none');
	     				        		d3.select('#win').style('display','none');
	     				        		//更新属性  
	     				        		initParams();
	     								return;
	     							}
	     						}
	     					},
	        	         error: function(data){jAlert("服务器请求异常",'提示');}
	        		});
	        		
	        	 }else{
	        		 jAlert("此属性编号已存在,请重新输入编号!",'提示');
	        	 }
	         },
	         error:function(data){jAlert("服务器访问异常!",'提示');}
		 });
		
		 
	}


});
//取消
d3.select('#addResBtn').on('click',function(){
	d3.select('#overlay').style('display','none');
	d3.select('#win').style('display','none');
});
//关闭
d3.select('#close').on('click',function(){
	d3.select('#overlay').style('display','none');
	d3.select('#win').style('display','none');
});

//=================添加属性end==============================================

//连线'添加属性' 点击事件
d3.select('#addBtn1').on('click',function(){
	addRow1();
	
});
//添加节点
function addRow1(){
	if(selected_link){
		if(selected_link.props){
			selected_link.props['']='未定义';
		}else{
			selected_link['props']={'':'未定义'};
		}
		updJson();
		showLink();
	}
}

function cancel(){
	for(var i=0;i<links.length;i++){//确保用户不提交的时候不出错
		 if(links[i].id==-1){
			// delete links[i];
			 links.splice(i, 1);
			 break;
		 }
	 }
};
//取消1
d3.select('#addResBtn1').on('click',function(){
	d3.select('#overlay1').style('display','none');
	d3.select('#win1').style('display','none');
});
//数据导入
d3.select("#importData").on("click",function(){
	d3.select('#overlay1').style('display','block');
	d3.select('#win1').style('display','block');
});
//上传
d3.select("#importBtn").on("click",function(){
	var name=d3.select("#importFile").property('value');
	var suffix=name.substring(name.lastIndexOf(".")+1,name.length);
	
	if(suffix!="xls" && suffix!="xlsx"){
		jAlert("请选择EXCEL文件!",'提示');
		return;
	}else{
		var form=$("#myform")[0];
		form.method="POST";
		form.action=window.basePath +"/api/cm/importFile";
		form.submit();
		jAlert("上传成功!",'提示');
		d3.select('#overlay1').style('display','none');
		d3.select('#win1').style('display','none');
	}
});






}]);